<template>
  <div class="reactive h-full">
    <div class="w-full">
      <div class="card">
        <div class="card-header">
          <div class="opacity-90 text-sm">待发布新闻（{{ pendingNews.length }}）</div>
        </div>
        <div class="divide-y">
          <div>
            <div v-if="sortedNews.length > 0">
              <div v-for="category in sortedNews" :key="category.id" class="category-section">
                <div class="category-header">
                  <span class="category-label"
                    >{{ category.label }}（{{ category.items.length }}）</span
                  >
                </div>
                <div v-if="category.items.length > 0" class="category-items">
                  <div
                    v-for="(news, index) in category.items"
                    :key="news.id"
                    class="news-item hover:bg-gray-50 transition"
                  >
                    <div class="flex justify-between items-center mb-3">
                      <div class="flex items-center gap-2 source-info">
                        <span class="font-medium text-gray-800">{{ news.source }}</span>
                        <el-tag type="primary" effect="dark" :color="getTag(news.classReal)?.color">
                          {{ getTag(news.classReal)?.label }}</el-tag
                        >
                      </div>
                      <div class="flex items-center gap-3">
                        <span class="text-gray-500 text-sm">{{ news.publishTime }}</span>
                        <span class="status-badge text-blue-500 bg-blue-50">待发布</span>
                        <span class="sort-icon cursor-pointer" @click="moveItemUp(news)">
                          <img :src="Arrow" alt="上移图标" title="上移" />
                        </span>
                        <span class="sort-icon rotate-180 cursor-pointer" @click="moveItemDown(news)">
                          <img :src="Arrow" alt="下移图标" title="下移" />
                        </span>
                      </div>
                    </div>

                    <div class="mb-2">
                      <div class="flex items-center gap-2.5 mb-2.5">
                        <span :class="categoryClass(news.category)" class="category-tag">
                          {{ news.category }}
                        </span>
                        <h3 class="title hover:text-blue-500 transition">
                          {{ news.title }}
                        </h3>
                      </div>

                      <p class="summary">{{ news.summary }}</p>

                      <div class="flex justify-between items-center mt-2">
                        <div class="flex items-center gap-2 author-info">
                          <span class="text-gray-700 text-sm">{{ news.author }}</span>
                        </div>
                        <div></div>
                        <div class="flex gap-3">
                          <el-popconfirm
                            title="确认要移除此新闻吗？"
                            @confirm="removeFromPending(news.id)"
                          >
                            <template #reference>
                              <el-button>移除</el-button>
                            </template>
                          </el-popconfirm>
                          <el-button @click="openDrawer(news)" class="btn-secondary"
                            >编辑</el-button
                          >
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="no-news">暂无待发布新闻</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { publishNews, updateNews, sortord } from '@/API/AllApi'
import { ref, onMounted, computed } from 'vue'
import Arrow from '@/assets/assets/circle-arrow.svg'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { categoryList } from '@/components/JournaLism/category'

const router = useRouter()
const pendingNews = ref([])
const loading = ref(false)
const error = ref('')
const Props = defineProps(['showBottomBtn'])

const sortField = ref('sequence')
const sortOredr = ref('desc')
const sortedNews = computed(() => {
  const categorizedNews = categoryList.map((cat) => ({
    id: cat.value,
    label: cat.label,
    color: cat.color,
    items: pendingNews.value.filter((item) => {
      const classRealNum =
        typeof item.classReal === 'string' ? parseInt(item.classReal) : item.classReal
      return classRealNum === cat.value
    }),
  }))

  return categorizedNews.filter((category) => category.items.length > 0)
})

const sortOptions = [
  { label: '发布时间', value: 'publishTime' },
  { label: '新闻标题', value: 'title' },
  { label: '新闻来源', value: 'source' },
]

const sorted = computed(() => {
  const categor = categoryList.map((cat) => ({
    id: cat.value,
    label: cat.label,
    color: cat.color,
    items: pendingNews.value
      .filter((item) => {
        const classRealNum =
          typeof item.classReal === 'string' ? parseInt(item.classReal) : item.classReal
        return classRealNum === cat.value
      })
      .sort((a, b) => {
        let aValue = a[sortField.value]
        let bValue = b[sortField.value]
        if (sortField.value === 'publishTime') {
          aValue = new Date(aValue)
          bValue = new Date(bValue)
        }
        return sortOredr.value === 'asc' ? aValue - bValue : bValue - aValue
      }),
  }))
})
const fetchNewsList = async () => {
  loading.value = true
  error.value = ''
  try {
    const result = await publishNews()
    const dataArray = Array.isArray(result.data) ? result.data : result.data?.list || []

    pendingNews.value = dataArray.map((item) => ({
      id: item.id || item.newsId || item.news_id || '',
      source: item.siteName || '',
      updater: item.opPerson || '',
      classReal: item.classReal || '',
      publishTime: item.newsTime || '',
      category: item.classModel || '',
      title: item.newsTitle || '',
      summary: item.abstractReal || '',
      author: item.newsSource || '',
      authorIcon: item.newsSource?.charAt(0).toUpperCase() || '?',
      originalData: item,
    }))

    if (pendingNews.value.length === 0) {
      ElMessage.info('暂无待发布新闻')
    }
  } catch (err) {
    console.error('获取待发布新闻列表失败:', err)
    error.value = '获取待发布新闻失败，请稍后重试'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

const removeFromPending = async (id) => {
  const res = await updateNews({ id, isSelect: 0 })
  if (res.code === 200) {
    ElMessage.success('新闻移除成功')
    pendingNews.value = pendingNews.value.filter((item) => item.id !== id)
  } else {
    ElMessage.error('新闻移除失败，请稍后重试')
  }
}
const openDrawer = (news) => {
  ElMessage.info('编辑功能待实现')
}


const getClassRealNum = (item) => {
  return typeof item.classReal === 'string' ? parseInt(item.classReal) : item.classReal;
};

const moveItem = async (news, direction) => {
  const list = pendingNews.value;
  const targetClassRealNum = getClassRealNum(news);

  const index = list.findIndex(
    item => item.id === news.id && getClassRealNum(item) === targetClassRealNum
  );

  if (index === -1) {
    ElMessage.warning('未找到该新闻');
    return;
  }

  let targetIndex, adjacentItem;
  if (direction === 'up') {
    if (index === 0) {
      ElMessage.warning('该新闻已经是当前分类的第一条');
      return;
    }
    adjacentItem = list[index - 1];
    targetIndex = index - 1;
  } else if (direction === 'down') {
    if (index === list.length - 1) {
      ElMessage.warning('该新闻已经是当前分类的最后一条');
      return;
    }
    adjacentItem = list[index + 1];
    targetIndex = index + 1;
  } else {
    return;
  }

  if (getClassRealNum(adjacentItem) !== targetClassRealNum) {
    ElMessage.warning(
      direction === 'up' 
        ? '该新闻已经是当前分类的第一条' 
        : '该新闻已经是当前分类的最后一条'
    );
    return;
  }

  [list[index], list[targetIndex]] = [list[targetIndex], list[index]];

  try {
    const sortList = list.map((item, idx) => ({
      id: item.id,
      orderNews: idx + 1
    }));
    const response = await sortord(sortList);

    if (response.code === 200) {
      ElMessage.success(direction === 'up' ? '新闻已上移' : '新闻已下移');
    } else {
      ElMessage.error('排序保存失败，请稍后重试');
      [list[index], list[targetIndex]] = [list[targetIndex], list[index]];
    }
  } catch (error) {
    console.error('排序保存失败:', error);
    ElMessage.error('排序保存失败，请稍后重试');
    [list[index], list[targetIndex]] = [list[targetIndex], list[index]];
  }
};

const moveItemUp = (news) => moveItem(news, 'up');

const moveItemDown = (news) => moveItem(news, 'down');





const getTag = (classReal) => {
  const classRealNum = typeof classReal === 'string' ? parseInt(classReal) : classReal
  return categoryList.find((item) => item.value === classRealNum) || {}
}

const categoryClass = (category) => {
  return {
    'bg-green-500': category === '宏观',
    'bg-red-500': category === '经济',
    'bg-blue-500': category === '行业',
  }
}

onMounted(async () => {
  await fetchNewsList()
})
</script>

<style scoped>
.card {
  background-color: #fff;
  border-radius: 0.5rem;
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.card-header {
  color: rgb(101, 100, 100);
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.news-item {
  padding: 1rem;
}
.divide-y {
  flex: 1;
  overflow-y: auto;
}

.p-8 {
  padding: 2rem;
}

.title {
  font-size: 1rem;
}

.btn-danger {
  background-color: #f87171;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
  cursor: pointer;
}

.btn-secondary {
  background-color: #a8dff7;
  color: white;
  padding: 0.5rem 1rem;
}

.Static {
  background-color: #0c77f2;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
  cursor: pointer;
}

.category-section {
  margin-bottom: 1rem;
}

.category-header {
  background-color: #f8fafc;
  padding: 0.75rem 1rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.category-items {
  margin-left: 0.5rem;
}

.cursor-pointer {
  cursor: pointer;
  transition: opacity 0.2s;
}

.cursor-pointer:hover {
  opacity: 0.7;
}

.no-news {
  text-align: center;
  padding: 2rem;
  color: #94a3b8;
}
</style>
